package com.mszlu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mszlu.blog.dao.mapper.BannedMapper;
import com.mszlu.blog.dao.mapper.SysUserMapper;
import com.mszlu.blog.dao.pojo.Admin;
import com.mszlu.blog.dao.pojo.Banned;
import com.mszlu.blog.dao.pojo.SysUser;
import com.mszlu.blog.service.LoginService;
import com.mszlu.blog.service.SysUserService;
import com.mszlu.blog.vo.*;
import com.mszlu.blog.vo.params.BannedParam;
import com.mszlu.blog.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Package: com.mszlu.blog.service.impl
 * @ClassName: SysUserServiceImpl
 * @Author: 陈威
 * @CreateTime: 2021/8/27 20:38
 * @Description:
 */
@SuppressWarnings("all")
@Service
public class SysUserServiceImpl implements SysUserService {
    //加盐
    private static final String slat = "mszlu!@#";
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    BannedMapper bannedMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    LoginService loginService;
    //sql预执行对象
    private LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();


    //根据id查询用户信息
    @Override
    public UserVo findUserById(Long authorId) {
        SysUser sysUser = sysUserMapper.selectById(authorId);
        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setId(1L);
            sysUser.setAvatar("/static/img/logo.b3a48c0.png");
            sysUser.setNickname("该作者未设置昵称.....");
        }
        UserVo userVo = new UserVo();
        userVo.setAccount(sysUser.getAccount());
        userVo.setAvatar(sysUser.getAvatar());
        userVo.setNickname(sysUser.getNickname());
        userVo.setId(String.valueOf(sysUser.getId()));
        return userVo;
    }

    //根据用户名密码查询所需的用户信息
    @Override
    public SysUser findUser(String account, String password) {
/*        queryWrapper.eq(SysUser::getAccount, account);  //设置参数 账号
        queryWrapper.eq(SysUser::getPassword, password); //设置参数 密码
        queryWrapper.select(SysUser::getNickname, SysUser::getAccount, SysUser::getAvatar, SysUser::getId); //设置返回的对象 使用对象只包含我们需要的数据
        queryWrapper.last("limit 1");
        return sysUserMapper.selectOne(queryWrapper);*/
        return sysUserMapper.findUser(account, password);

    }

    @Override
    public Result fingUserByToken(String token) {

        /*
         1.token合法性校验
            是否为空,解析是否成功 redis是否存在
            2.如果校验失败返回错误
            3.如果检验成功，返回对应的结果

         **/
        //判断redis中是否有该token 如果有就解析该token并获取token中存储的用户信息
        SysUser sysUser = loginService.checkToken(token);
        Admin admin = loginService.checkAdminToken(token);
        if (admin != null) {
            Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
            LoginUserVo loginUserVo = new LoginUserVo();
            loginUserVo.setAccount(admin.getAccount());
            loginUserVo.setAvatar(admin.getAvatar());
            loginUserVo.setId(String.valueOf(admin.getId()));
            return Result.success(loginUserVo);
        }
        if(sysUser!=null){
            LoginUserVo loginUserVo = new LoginUserVo();
            loginUserVo.setAccount(sysUser.getAccount());
            loginUserVo.setAvatar(sysUser.getAvatar());
            loginUserVo.setId(String.valueOf(sysUser.getId()));
            loginUserVo.setNickname(sysUser.getNickname());
            return Result.success(loginUserVo);
        }


        return Result.fail(999,"系统错误");
    }

    //根据用户名查询数据库有无该用户
    @Override
    public SysUser findUserByAccount(String account) {
        queryWrapper.eq(SysUser::getAccount, account); //设置参数
        queryWrapper.last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        return sysUser;
    }

    //插入注册
    @Override
    public void save(SysUser sysUser) {
        //默认生成的id使用了雪花算法
        sysUserMapper.insert(sysUser);
    }

    @Override
    public Result updatePwd(LoginParam param) {
        if (param == null) {
            return Result.fail(999, "参数有误");
        }
        if (param.getId() == null) {
            return Result.fail(999, "参数有误");
        }
        SysUser sysUser = sysUserMapper.selectById(param.getId());
        String password = param.getPassword();
        password = DigestUtils.md5Hex(password + slat);
        sysUser.setAccount(param.getAccount());
        sysUser.setNickname(param.getNickname());
        sysUser.setPassword(password);

        sysUserMapper.updateById(sysUser);

        return Result.success(null);
    }

    //封号
    @Override
    public Result bannedAccount(BannedParam bannedParam, String token) {
        Admin admin = loginService.checkAdminToken(token);
        SysUser sysUser = sysUserMapper.selectById(bannedParam.getUid());
        if (admin != null && sysUser != null) {
            Banned banned = new Banned();
            try {
                banned.setAccount(sysUser.getAccount());
                banned.setCreateDate(System.currentTimeMillis());
                banned.setReason(bannedParam.getReason());
                banned.setOperation(admin.getAccount());
                banned.setUid(sysUser.getId());
                if ("1".equals(bannedParam.getBannedType())) {
                    banned.setBannedType(BannedCode.BANNED_CODE_ONE.getCode());
                    banned.setBannedCode(System.currentTimeMillis()+(long) (1000L * 60 * 60 * 24 * 7));
                } else if ("2".equals(bannedParam.getBannedType())) {
                    banned.setBannedType(BannedCode.BANNED_CODE_TWO.getCode());
                    banned.setBannedCode(System.currentTimeMillis()+(long) (1000L * 60 * 60 * 24 * 90));
                } else {
                    banned.setBannedType(BannedCode.BANNED_CODE_THREE.getCode());
                    banned.setBannedCode(System.currentTimeMillis()+(long) (1000L * 60 * 60 * 24 * 90 * 90));
                }
                bannedMapper.insert(banned);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail(999, "封禁失败");
            }
        }
        return Result.success(null);
    }

    @Override
    public Result unlockAccount(Long uid) {
        LambdaUpdateWrapper<Banned> updateWrapper=new LambdaUpdateWrapper<>();
        try {
            updateWrapper.eq(Banned::getUid,uid);
            bannedMapper.delete(updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(999, "解封失败");
        }

        return Result.success(null);
    }
}